package cn.com.dragonsoftbravo.utils.web;

import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.web.context.support.WebApplicationContextUtils;

/* 
 *
 * @copyright Promoters Sell-thru System, ISSG, Sony China
 *
 * @author Dennis Ge
 * @date 2011-4-1
 * @version 0.1
 */

public abstract class WebContextUtils {

	/**
	 * Gets the bean in the ServletContext
	 * Only fetch the first bean matched the target type from Spring context
	 * 
	 * @param <T>
	 *            the generic type
	 * @param context
	 *            the context
	 * @param type
	 *            the type
	 * @return the first bean if there is any bean matched, otherwise return null
	 */
	public static <T> T getBean(ServletContext context, Class<T> type) {

		Map<String, T> beans = WebApplicationContextUtils.getWebApplicationContext(context)
				.getBeansOfType(type);

		if (beans.isEmpty()) {
			return null;
		} else {
			return (T) beans.entrySet().iterator().next().getValue();
		}
	}
}
